package com.ww.core.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;

/**
 * 图片工具类.
 * @since 
 * @version 2012-10-16
 * @author wangw
 */
public class ImageUtil {
	public static  String IMAGEPATH = Environment.getExternalStorageDirectory() + "/daydayup/image/";
	private static Map<String, Bitmap> map = new HashMap<String, Bitmap>();

	public ImageUtil(String path){
		this.IMAGEPATH=path;
		File f = new File(IMAGEPATH);
		if (!f.exists()) {
			f.mkdirs();
		}
	
	}

	/**
	 * 获取图片. 首先从内存里取图片,没有的话 从本地sdcard取图片并保存在map里,
	 * 本地没有图片的话, 从网络上把图片取下来,保存在sdcard上,在保存在map里
	 * @param fileUrl 图片网络地址
	 * @return bitmap对象
	 */
	public static Bitmap getImage(String fileUrl) {
		try {
			String filePath = IMAGEPATH + filterPath(fileUrl);
			// 首先从内存里取图片
			Bitmap bitmap = map.get(filePath);
			if (bitmap != null) {
				Logger.info("getImage from map");
				return bitmap;
			}

			// 从本地sdcard取图片
			if (new File(filePath).exists()) {
				bitmap = BitmapFactory.decodeFile(filePath);
				put(filePath, bitmap);
				Logger.info("getImage from sdcard   " + filePath);
				return bitmap;
			}

			// 从网络上去图片，并保存在本地，并存储在map里
			bitmap = returnBitMap(fileUrl);
			if (bitmap != null) {
				Logger.info("getImage from network");
				put(filePath, bitmap);
				saveBitmap(bitmap, IMAGEPATH, filterPath(fileUrl));
			}
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static void put(String key, Bitmap value) {
		Object s[] = map.keySet().toArray();
		if (map.size() < 100) {
			map.put(key, value);
		} else {
			map.remove(s[0]);

			if (!map.get(key).isRecycled()) {
				map.get(key).recycle(); //回收图片所占的内存
			}
			map.put(key, value);
		}

	}

	/**
	 * 下载网络图片.
	 * @param fileUrl 图片地址
	 * @param fileName 图片名称
	 */
	public  void saveImage(final String fileUrl, final String fileName) {
		new Thread() {
			@Override
			public void run() {
				Bitmap b = returnBitMap(fileUrl);
				try {
					String type = contain(fileUrl);
					saveBitmap(b, IMAGEPATH, fileName + type);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 获取图片链接的后缀名.
	 * @param fileUrl 图片链接
	 * @return 图片后缀名  (".gif", ".jpg", ".jpeg",".bmp", ".png")
	 */
	private static String contain(String fileUrl) {
		String[] strings = new String[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
		for (int i = 0; i < strings.length; i++) {
			String s = strings[i];
			if (fileUrl.contains(s))
				return s;
		}
		return ".jpg";
	}

	/**
	 * 下载网络图片.
	 * @param fileUrl 图片地址
	 */
	public static void downloadCache(final String fileUrl) {
		new Thread() {
			@Override
			public void run() {
				Bitmap b = returnBitMap(fileUrl);
				try {
					saveBitmap(b, IMAGEPATH, fileUrl);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 将网络图片转换为bitmap对象.
	 * @param url  图片地址
	 * @return Bitmap
	 */
	private static Bitmap returnBitMap(String url) {
		if (null == url || "".equals(url)) {
			return null;
		} else {
			URL myFileUrl = null;
			Bitmap bitmap = null;
			try {
				myFileUrl = new URL(url);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
			try {
				HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
				conn.setConnectTimeout(5000);
				conn.setReadTimeout(3000);
				conn.setDoInput(true);
				conn.connect();
				InputStream is = conn.getInputStream();
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = false;
				options.inSampleSize = 2; //width，hight设为原来的十分一
				bitmap = BitmapFactory.decodeStream(is, null, options);
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bitmap;
		}
	}

	/**
	 * 保存bitmap对象为图片文件.
	 * @param bm Bitmap
	 * @param root 保存路径
	 * @param fileUrl    文件名
	 * @throws IOException  IOException
	 */
	public static void saveBitmap(final Bitmap bm, final String root, final String fileUrl) {
		new Thread() {
			@Override
			public void run() {
				File myCaptureFile = new File(root + filterPath(fileUrl));
				BufferedOutputStream bos;
				try {
					bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
					bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
					bos.flush();
					bos.close();
					super.run();
					Logger.info("saveBitmap ok  " + root + fileUrl);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 将网络图片转换为.
	 * @param fileUrl InputStream
	 * @return InputStream
	 */
	public static InputStream getInputStreamByImage(String fileUrl) {
		try {
			Bitmap bitmap = returnBitMap(fileUrl);
			if (bitmap != null) {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
				InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
				return sbs;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 过滤网络连接的特殊字符.
	 * @param x  网络链接
	 * @return 过滤后的连接
	 */
	private static String filterPath(String x) {
		return x.replace("\\", "/").replace("?", "").replace("/", "").replace(":", "");
	}

	/** 
	 * 获取图片名称获取图片的资源id的方法 .
	 * @param context Context
	 * @param imageName 图片名称 
	 * @return  资源id
	 */
	public static int getResource(Context context, String imageName) {
		int resId = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
		return resId;
	}

	public static Drawable getDrawable(Context context, int resource) {
		Resources res = context.getResources();
		return res.getDrawable(resource);
	}

}
